package com.wecloud.core.server;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.wecloud.core.constant.ErrorMsg;
import com.wecloud.core.constant.WeContext;
import com.wecloud.core.exception.WeException;
import com.wecloud.core.user.WeUser;
import com.wecloud.redis.service.RedisService;

public class InitContext {
	 @Autowired
	 private RedisService redisService;//redis
	 
	 @Autowired
	 private UploadFilesServer server;
	 
	 public  WeContext init(Map param,HttpServletRequest req,HttpServletResponse resp) throws WeException, UnsupportedEncodingException, InterruptedException, ExecutionException{
		WeContext context = new WeContext();
		context.setRequest(req);
		context.setResp(resp);
		context.setTransactionId(param.get("uri").toString());
		context.setData(param);
		WeUser user = null;
//		//注册请求
		if("register".equals(param.get("uri"))){
			context.setData("uri",param.get("uri"));
			return context;
		}
		if(param.get("JSESSIONID") != null && !"".equals(param.get("JSESSIONID"))
				&& !"login".equals(param.get("uri")) && !"queryUserIsFirstLogin".equals(param.get("uri"))
				){
			user = redisService.get((String)param.get("JSESSIONID"));
			if(user == null){
				 throw new WeException(ErrorMsg.Error_0003);
			}
			context.setUser(user);
		}
		if("upload".equals(param.get("uri"))){
			if(user == null){
				 throw new WeException(ErrorMsg.Error_0003);
			}
			context.setData("uri",param.get("uri"));
			//处理文件信息
			context.setData("List", server.execute(context).get());
		}
		return context;
	 }
}
